package com.foreknow.controller;


import com.foreknow.model.Guestbook;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;


public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");


        GuestbookServiceImpl guestbookService = new GuestbookServiceImpl();
        Guestbook guestbook = new Guestbook();
        guestbook.setName(name);
        guestbook.setPhone(phone);
        guestbook.setEmail(email);
        guestbook.setTitle(title);
        guestbook.setContent(content);


        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        guestbook.setCreatedTime(format);


        if (guestbookService.add(guestbook)){
//            out.println("<a href='find'>超链接</a>");
            // 转发资源（请求转发）
//            req.getRequestDispatcher("/find").forward(req,resp);
            //重定向
            resp.sendRedirect(req.getContextPath()+"/find");
//            resp.sendRedirect("http://www.baidu.com);
        }else {
            out.println("添加失败");
        }


    }
}
